package com.jcgyl.export.task;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.UnableToInterruptJobException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcgyl.export.dao.CustomerDao;
import com.jcgyl.export.dao.TbuploadDetailDao;
import com.jcgyl.export.dao.TbuploadinfoDao;
import com.jcgyl.export.entity.Customer;
import com.jcgyl.export.entity.TbInventoryBody;
import com.jcgyl.export.entity.TbInventoryHead;
import com.jcgyl.export.entity.Tbbcusunit;
import com.jcgyl.export.entity.Tbciqmoney;
import com.jcgyl.export.entity.Tbciqpckagetype;
import com.jcgyl.export.entity.Tbcuscountry;
import com.jcgyl.export.entity.Tbdictionary;
import com.jcgyl.export.entity.Tbedpinfo;
import com.jcgyl.export.entity.Tbgoodsinfo;
import com.jcgyl.export.entity.Tblogisticinfo;
import com.jcgyl.export.entity.Tborderhead;
import com.jcgyl.export.entity.Tborderlist;
import com.jcgyl.export.entity.Tbpayinfo;
import com.jcgyl.export.entity.Tbuploaddetail;
import com.jcgyl.export.entity.Tbuploadinfo;
import com.jcgyl.export.entity.Tbwaybill;
import com.jcgyl.export.mapper.TbInventoryBodyMapper;
import com.jcgyl.export.mapper.TbInventoryHeadMapper;
import com.jcgyl.export.mapper.TbedpinfoMapper;
import com.jcgyl.export.mapper.TblogisticinfoMapper;
import com.jcgyl.export.mapper.TborderheadMapper;
import com.jcgyl.export.mapper.TborderlistMapper;
import com.jcgyl.export.mapper.TbpayinfoMapper;
import com.jcgyl.export.mapper.TbuploaddetailMapper;
import com.jcgyl.export.mapper.TbuploadinfoMapper;
import com.jcgyl.export.mapper.TbwaybillMapper;
import com.jcgyl.export.model.SocketMessage;
import com.jcgyl.export.model.SystemConstants;
import com.jcgyl.export.model.UnitCategory;
import com.jcgyl.export.mq.MessageSender;
import com.jcgyl.export.service.Impl.InventoryServiceImpl;
import com.jcgyl.export.service.Impl.OrderServiceImpl;
import com.jcgyl.export.service.Impl.PayInfoServiceImpl;
import com.jcgyl.export.service.Impl.WaybillServiceImpl;
import com.jcgyl.export.util.DictionaryHelper;
import com.jcgyl.export.util.DictionaryType;
import com.jcgyl.export.util.GoodsHelper;
import com.jcgyl.export.util.MessageHelper;
import com.jcgyl.export.websocket.ProcessWebSocketHandler;

public class OrderProcessTask implements InterruptableJob {
	protected static Logger logger = LoggerFactory.getLogger(OrderProcessTask.class);
	private HashMap<String, Tbuploaddetail> detail_table = new HashMap<String, Tbuploaddetail>();

	private TbedpinfoMapper tbedpinfoMapper;
	private TblogisticinfoMapper tblogisticinfoMapper;
	private TbuploadinfoMapper tbuploadinfoMapper;
	private TbuploaddetailMapper tbuploaddetailMapper;
	private TbuploadDetailDao tbuploadDetailDao;
	private TbpayinfoMapper tbpayinfoMapper;
	private TborderheadMapper tborderheadMapper;
	private TborderlistMapper tborderlistMapper;
	private TbwaybillMapper tbwaybillMapper;
	private TbInventoryHeadMapper tbinventoryheadMapper;
	private TbInventoryBodyMapper tbinventorybodyMapper;
	private WaybillServiceImpl waybillServiceImpl;
	private TbuploadinfoDao tbuploadinfoDao;
	private InventoryServiceImpl inventoryServiceImpl;

	private OrderServiceImpl orderServiceImpl;

	private PayInfoServiceImpl payInfoServiceImpl;
	// 批量插入
	@Resource
	private MessageSender messageSender;

	private CustomerDao customerDao;

	public OrderProcessTask() {

	}

	private volatile boolean isJobInterrupted = false;
	private JobKey jobKey = null;
	private volatile Thread thisThread;

	public void interrupt() throws UnableToInterruptJobException {
		System.out.println("my job:" + jobKey + "  -- INTERRUPTING --");
		isJobInterrupted = true;
		if (thisThread != null) {
			thisThread.interrupt();
		}
	}

	public void execute(JobExecutionContext context) throws JobExecutionException {
		thisThread = Thread.currentThread();
		jobKey = context.getJobDetail().getKey();
		System.out.println("my job:" + jobKey + " executing at " + new Date());
		try {
			if (isJobInterrupted) {
				System.out.println("my job:" + jobKey + "  -- Interrupted... bailing out!");
				return;
			} else {
				tbedpinfoMapper = (TbedpinfoMapper) context.getJobDetail().getJobDataMap().get("tbedpinfoMapper");
				tblogisticinfoMapper = (TblogisticinfoMapper) context.getJobDetail().getJobDataMap()
						.get("tblogisticinfoMapper");
				tbuploadinfoMapper = (TbuploadinfoMapper) context.getJobDetail().getJobDataMap()
						.get("tbuploadinfoMapper");
				tbuploaddetailMapper = (TbuploaddetailMapper) context.getJobDetail().getJobDataMap()
						.get("tbuploaddetailMapper");
				tbuploadDetailDao = (TbuploadDetailDao) context.getJobDetail().getJobDataMap().get("tbuploadDetailDao");
				tborderheadMapper = (TborderheadMapper) context.getJobDetail().getJobDataMap().get("tborderheadMapper");
				tborderlistMapper = (TborderlistMapper) context.getJobDetail().getJobDataMap().get("tborderlistMapper");
				tbwaybillMapper = (TbwaybillMapper) context.getJobDetail().getJobDataMap().get("tbwaybillMapper");
				tbpayinfoMapper = (TbpayinfoMapper) context.getJobDetail().getJobDataMap().get("tbpayinfoMapper");
				tbinventoryheadMapper = (TbInventoryHeadMapper) context.getJobDetail().getJobDataMap()
						.get("tbinventoryheadMapper");
				tbinventorybodyMapper = (TbInventoryBodyMapper) context.getJobDetail().getJobDataMap()
						.get("tbinventorybodyMapper");
				customerDao = (CustomerDao) context.getJobDetail().getJobDataMap().get("customerDao");
				waybillServiceImpl = (WaybillServiceImpl) context.getJobDetail().getJobDataMap()
						.get("waybillServiceImpl");
				inventoryServiceImpl = (InventoryServiceImpl) context.getJobDetail().getJobDataMap()
						.get("inventoryServiceImpl");
				orderServiceImpl = (OrderServiceImpl) context.getJobDetail().getJobDataMap().get("orderServiceImpl");
				payInfoServiceImpl = (PayInfoServiceImpl) context.getJobDetail().getJobDataMap()
						.get("payInfoServiceImpl");
				tbuploadinfoDao = (TbuploadinfoDao) context.getJobDetail().getJobDataMap().get("tbuploadinfoDao");
				messageSender = (MessageSender) context.getJobDetail().getJobDataMap().get("messageSender");
				int upload_id = context.getJobDetail().getJobDataMap().getInt("upload_id");
				int customer_id = context.getJobDetail().getJobDataMap().getInt("customerId");
				String edpCompanyId = context.getJobDetail().getJobDataMap().getString("edpCompanyId");
				String edpPlatformId = context.getJobDetail().getJobDataMap().getString("edpPlatformId");
				String logisticId = context.getJobDetail().getJobDataMap().getString("logisticId");
				String weightUnit = context.getJobDetail().getJobDataMap().getString("weightUnit");
				int jcbPort = context.getJobDetail().getJobDataMap().getInt("jcbPort");
				int applyPort = context.getJobDetail().getJobDataMap().getInt("applyPort");
				String transferRegionInSp = context.getJobDetail().getJobDataMap().getString("transferRegionInSp");

				logger.error("获取参数...");
				// 获取一个运单对应多个商品的情况
				// var express_numbers = GetMoreThanOneExpressNumber(value.uploadId);
				// 生成实体存到数据库
				Tbuploadinfo tbuploadinfo = tbuploadinfoMapper.selectByPrimaryKey(upload_id);
				List<Tbuploaddetail> orders = GetDuplicateOrder(upload_id);
				for (Tbuploaddetail tbuploaddetail : orders) {
					detail_table.put(tbuploaddetail.getExpressNumber(), tbuploaddetail);
				}
				tbuploadinfo.setEdpCompanyId(edpCompanyId);
				tbuploadinfo.setEdpPlatformId(edpPlatformId);
				tbuploadinfo.setLogisticId(logisticId);
				tbuploadinfoMapper.updateByPrimaryKey(tbuploadinfo);
				// 获取电商信息
				Tbedpinfo edp_company = tbedpinfoMapper.selectByPrimaryKey(new Integer(edpCompanyId));
				Tbedpinfo edp_platform = tbedpinfoMapper.selectByPrimaryKey(new Integer(edpPlatformId));
				logger.error("获取订单...");
				Tblogisticinfo tblogisticinfo = tblogisticinfoMapper.selectByPrimaryKey(new Integer(logisticId));
				List<Tbuploaddetail> distinct_orders = GetDistinctOrder(upload_id);
				Integer index = 1;
				List<Tbwaybill> waybills = new ArrayList<Tbwaybill>();
				List<Tborderhead> heads = new ArrayList<Tborderhead>();
				List<Tborderlist> order_lists = new ArrayList<Tborderlist>();
				List<Tbpayinfo> pay_infos = new ArrayList<Tbpayinfo>();
				List<TbInventoryHead> inventory_heads = new ArrayList<TbInventoryHead>();
				List<TbInventoryBody> inventory_lists = new ArrayList<TbInventoryBody>();

				if (distinct_orders != null) {
					for (Tbuploaddetail tbuploaddetail : distinct_orders) {
						Tbwaybill way_bill = GenerateWayBill(tbuploaddetail, edp_company, edp_platform, tblogisticinfo,
								weightUnit, jcbPort, applyPort, transferRegionInSp);
						Tborderhead order_head = GenerateOrderHead(tbuploaddetail, edp_company, edp_platform,
								tblogisticinfo, way_bill, customer_id);
						logger.error("生成标体...");
						List<Tborderlist> order_list = GenerateOrderList(tbuploaddetail, way_bill);
						Tbpayinfo pay_info = GeneratePayInfo(tbuploaddetail, edp_company, edp_platform, tblogisticinfo,
								order_head);
						TbInventoryHead inventory_head = GenerateInventoryHead(order_head, way_bill, pay_info,
								tbuploaddetail, edp_company, edp_platform, tblogisticinfo, weightUnit, jcbPort,
								applyPort, transferRegionInSp);
						way_bill.setUploadId(upload_id);
						order_head.setUploadid(Integer.toString(upload_id));
						pay_info.setUploadid(upload_id);
						logger.error("准备插入数据库...");
						heads.add(order_head);
						for (Tborderlist tborderlist : order_list) {
							order_lists.add(tborderlist);
						}
						waybills.add(way_bill);
						// inventory_heads.add(inventory_head);
						tbinventoryheadMapper.insert(inventory_head);
						pay_infos.add(pay_info);
						List<TbInventoryBody> inventory_bodies = GenerateInventoryBody(order_head, way_bill, pay_info,
								tbuploaddetail, edp_company, edp_platform, tblogisticinfo, weightUnit, jcbPort,
								applyPort, transferRegionInSp);
						for (TbInventoryBody inventory_body : inventory_bodies) {
							inventory_body.setInventoryHeadId(inventory_head.getInventoryId());
							inventory_lists.add(inventory_body);
						}
						String order_msg = MessageHelper.GenerateOrderMessage(order_head, order_list);
						String waybill_msg = MessageHelper.GenerateExpressMessage(way_bill);
						String pay_msg = MessageHelper.GeneratePayMessage(pay_info);
						String inventory_msg = MessageHelper.GenerateInventoryMessage(inventory_head, inventory_bodies);
						messageSender.send(order_msg);
						messageSender.send(waybill_msg);
						messageSender.send(pay_msg);
						Thread.currentThread().sleep(2000);
						messageSender.send(inventory_msg);
						// 通知客户端生成进度
						SocketMessage message = new SocketMessage();
						message.messageType = "send";
						message.message = "{\"upload_id\":" + upload_id + ",\"index\":" + index + "}";
						ObjectMapper objectMapper = new ObjectMapper();
						ProcessWebSocketHandler.sendInfo(objectMapper.writeValueAsString(message));

						logger.info("推送完成...");
						index++;
					}
					int batch_size = 30;
					int total_count = distinct_orders.size();
					tbuploadinfoDao.UpdateUploadInfoSendCount(total_count, upload_id);
					int max_interator = (int) Math.ceil(total_count * 1.0 / batch_size);
					for (int j = 0; j < max_interator; j++) {
						int max_index = Math.min((j + 1) * batch_size, total_count);
						int start_index = j * batch_size;
						waybillServiceImpl.batchInsert(waybills.subList(start_index, max_index));
						logger.error("批量保存运单成功...");
						orderServiceImpl.batchInsertHeads(heads.subList(start_index, max_index));
						logger.error("批量保存订单表头成功...");
						payInfoServiceImpl.batchInsert(pay_infos.subList(start_index, max_index));
						logger.error("批量保存支付单成功...");
						// inventoryServiceImpl.batchInsertInventoryHeads(inventory_heads.subList(start_index,
						// max_index));
						// logger.error("批量保存清单表头成功...");
					}

					batch_size = 20;
					total_count = order_lists.size();
					max_interator = (int) Math.ceil(total_count * 1.0 / batch_size);
					for (int j = 0; j < max_interator; j++) {
						int max_index = Math.min((j + 1) * batch_size, total_count);
						int start_index = j * batch_size;
						orderServiceImpl.batchInsertBodies(order_lists.subList(start_index, max_index));
						logger.error("批量保存订单表体30单成功...");
						inventoryServiceImpl
								.batchInsertInventoryBodies(inventory_lists.subList(start_index, max_index));
						logger.error("批量保存清单30单成功...");
					}
				}
			}
		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			String sStackTrace = sw.toString(); // stack trace as a string
			System.out.println(sStackTrace);
			logger.error(sStackTrace);
			logger.error(e.getMessage());
		} finally {
		}
	}

	private Tbwaybill GenerateWayBill(Tbuploaddetail order, Tbedpinfo edp_company, Tbedpinfo edp_platform,
			Tblogisticinfo logistic, String weight_unit, int jcbPort, int applyPort, String transferRegionInSp) {
		Tbwaybill bill = new Tbwaybill();
		bill.setUploadId(order.getUploadId());
		bill.setExpressNumber(order.getExpressNumber());
		bill.setTotalTransferNumber(order.getSerialNumber());
		bill.setTarnsferNumber(order.getExpressNumber());
		// 主单号
		bill.setBillNo(order.getMainNumber());
		// 订单编号，同运单号
		bill.setOrderId(order.getExpressNumber().replace("LVS", ""));
		// 物流企业名称
		bill.setDeliverEnterpriseName(logistic.getLogisticName());
		// 物流企业代码
		bill.setDeliverEnterpriseCode(logistic.getLogisticCode());
		// 模式代码,待确认默认值
		bill.setBillMode(DictionaryHelper.GetDefaultValue(DictionaryType.BillMode).getDictionariecode());
		// 收货人国家,取字典,此处需要根据国家缩写获取代码
		Tbcuscountry country = DictionaryHelper.GetCountryByAbbre(order.getState().trim());
		bill.setCollectionUserCountry(country.getCustomscode());
		bill.setCollectionUserCountryInsp(country.getCountrycode());
		// 收货人地址
		bill.setCollectionUserAddress(order.getReceiverAddress().trim());
		// 收货人名称
		bill.setCollectionUserName(order.getReceiverName());
		// 收货人电话
		bill.setCollectionUserTelephone("_");
		// 发货人所在国
		bill.setSenderCountry("142");
		// 发货人姓名
		bill.setSenderName(order.getShipper());
		// 境内运费，默认0
		bill.setFreight(new BigDecimal(0));
		// 包装种类,字典
		// varpackage_category(DictionaryHelper.GetDefaultValue(DictionaryType.PackageCategory));
		Tbdictionary package_category = DictionaryHelper.GetDictionaryByName(DictionaryType.PackageCategory,
				order.getPackageType());
		bill.setPackageCategory(package_category.getDictionariecode());
		// 件数
		bill.setPackNum(1);
		// 毛重
		bill.setWeight(GetStandardWeight(order.getRoughWeight(), weight_unit));
		// 净重,
		bill.setNetWeight(GetTotalNetWeightOfOrder(order));

		// 数量,针对一对多的清醒，这里应该计算总数
		// bill.setamount(int.Parse(order.count));
		bill.setAmount(GetTotalAmountOfOrder(order));
		// 运输工具名称，字典，默认飞机
		Tbdictionary dict_ship = DictionaryHelper.GetDefaultValue(DictionaryType.ShipName);
		bill.setShipName(dict_ship.getDictionariename());
		// 进出口标志，字典，默认E
		bill.setIdType(DictionaryHelper.GetDefaultValue(DictionaryType.IeType).getDictionariecode());
		// 贸易国别，同收货人国家
		bill.setTradeCountry(country.getCustomscode());
		// 操作类型，默认1
		bill.setModifyMask("1");
		// 进出境口岸，字典，默认
		Tbdictionary dict_port = DictionaryHelper.GetValueById(jcbPort);
		// bill.setjcbOrderPort(DictionaryHelper.GetDefaultValue(DictionaryType.JcbOrderPOrInSp).dictionarieCode);
		bill.setJcbOrderPort(dict_port.getDictionariecode());
		// 运输方式代码，与运输工具名称对应
		Tbdictionary dict_transfertype = DictionaryHelper.GetDefaultValue(DictionaryType.TransportMode);
		bill.setTransferType(dict_transfertype.getDictionariecode());
		// 检疫检验运输工具代码，与运输工具名称对应
		Tbdictionary dict_ciq_transfertype = DictionaryHelper.GetDefaultValue(DictionaryType.CIQShipName);
		bill.setShipCodeInsp(dict_ciq_transfertype.getDictionariecode());
		// 运输工具代码（海关）
		Tbdictionary dict_transfer = DictionaryHelper.GetDefaultValue(DictionaryType.ShipName);
		bill.setShipCode(dict_transfer.getDictionariecode());
		// 检验检疫运输方式代码
		bill.setTransferTypeInsp(dict_transfertype.getDictionariecode());
		// 检验检疫运输工具名称 非必填
		bill.setShipNameInsp(dict_ship.getDictionariename());

		// 检疫检验包装种类，跟海关的包装种类不同，请注意
		Tbciqpckagetype ciq_package_category = DictionaryHelper
				.GetCiqPackageType(package_category.getDictionariename());
		bill.setPackCategoryInsp(ciq_package_category == null ? "9999" : ciq_package_category.getPackTypeCode());
		// 物流企业检疫检验备案编号，
		bill.setLogisticsCodeInsp(logistic.getCiqCode());

		// 电商企业检疫检验备案编号
		bill.setCbeCodeInsp(edp_company.getCiqCode());
		// 电商企业海关备案编号
		bill.setCbeCode(edp_company.getCustomCode());
		// 申报口岸，与进出境口岸对应
		bill.setDeclarePort(bill.getJcbOrderPort());
		// 批次号
		bill.setTotalTransferNumber(order.getSerialNumber());
		// 装运港、指运港
		bill.setDestinationPort(order.getHarbour());

		// 检验检疫进/出境口岸
		Tbdictionary dict_applyport = DictionaryHelper.GetValueById(applyPort);
		// bill.setjcbOrderOrPorTInSP(DictionaryHelper.GetDefaultValue(DictionaryType.ApplyPOrInSp).dictionarieCode);
		bill.setJcbOrderOrPortInsp(dict_applyport.getDictionariecode());
		// 检疫检验申报口岸代码，默认
		bill.setApplyPortInsp(dict_applyport.getDictionariecode());
		// 检验检疫起运国/抵运国,同收件人所在国,或者指运港所在国，注意，指运港的代码是海关代码需要转换成商检代码,1代表收件人所在国
		if (transferRegionInSp.equals("1")) {
			bill.setTransferRegionInsp(country.getCountrycode());
			bill.setInspCountryCode(country.getCountrycode());
			/// 抵运港（国检）
			bill.setArrivedPort(country.getCountrycode());
		} else {
			Tbcuscountry ciq_country = DictionaryHelper.GetCountryByCustomsCode(order.getHarbour());
			bill.setTransferRegionInsp(ciq_country.getCountrycode());
			bill.setInspCountryCode(ciq_country.getCountrycode());
			/// 抵运港（国检）
			bill.setArrivedPort(ciq_country.getCountrycode());
		}
		// 发货人国家代码（国检）
		bill.setShipperCountryInsp("156");
		// 电商企业名称
		bill.setCbeName(edp_company.getName());
		// 电商平台代码 非必填
		bill.setEcpCode(edp_platform.getName());
		// 电商平台名称 非必填-
		bill.setEcpName(edp_platform.getName());
		// 物流跟踪号
		bill.setTrackNo("");
		// 物流跟踪状态
		bill.setTrackStatus("");

		Customer customer = customerDao.findByName(order.getShipper());
		// 发货人的名称 非必填
		bill.setSenderName(logistic.getLogisticName());

		// 发货人的地址 非必填-
		bill.setSenderAddress(customer.getAddress());
		// 发货人电话 非必填
		bill.setSenderTelephone(customer.getPhone());
		// 证件号码 非必填
		bill.setCustomerId("");
		// 申报日期 非必填
		bill.setDeclareDate(new Date());
		// 跨境运费 非必填
		bill.setCrossFreight(new BigDecimal(0.0));
		// 商品名称，非必填
		bill.setGoodsName(order.getProductName());
		bill.setRemark("");
		// 币制（检验检疫代码）节点可空 非必填
		Tbciqmoney coin = DictionaryHelper.GetCoinByAbbreviation(order.getCurrency());
		bill.setCoinInsp(coin.getCountrycode());
		bill.setSendStatus("send");
		// 进出境日期
		bill.setJcbOrderTime(new Date());
		// 运单提交日期
		bill.setSubmitTime(new Date());
		// 价值外币（国检）
		bill.setTotalValue(new BigDecimal(order.getTotalPrice()));
		// body_master. TOTALVALUE=bill.getto;
		// 监管机构代码(国检)
		bill.setRegulatorcode(bill.getJcbOrderOrPortInsp());
		// 监管机构名称（国检）
		bill.setRegulatorname(dict_applyport.getDictionariename());
		/// 进出口标志（国检）
		bill.setInOutFlag("O");
		// 进出口标志（海关）
		bill.setIeType("E");
		// 进出口模式（国检）
		bill.setImportType("0");
		/// 码头/货场代码（国检）
		bill.setGoodsYardCode("156286");
		// 发货人城市(国检)
		bill.setShipperCity("410100");
		// body_master. SHIPPERCITY=bill.getshi;
		// 装运港/指运港（国检）
		bill.setIsnpDestinationPort(order.getHarbourInsp());
		// 起运国/抵运国（国检）
		bill.setInspCountryCode(order.getDestinationCountryInsp());
		// 起运国/抵运国（海关）
		bill.setDestinationCountryCus(order.getDestinationCountryCus());
		bill.setArrivedPort("554003");
		return bill;

	}

	public Tborderhead GenerateOrderHead(Tbuploaddetail order, Tbedpinfo edp_company, Tbedpinfo edp_platform,
			Tblogisticinfo logistic, Tbwaybill waybill, int customerId) {
		Tborderhead order_head = new Tborderhead();
		order_head.setCustomerid(customerId);
		order_head.setExpressnumber(order.getExpressNumber());
		// 电商海关备案编号
		order_head.setCbecode(edp_company.getCustomCode());
		// 模式代码
		order_head.setBillmode("1");
		// 电商海关备案名称
		order_head.setCbename(edp_company.getName());
		// 电商平台代码
		order_head.setEcpcode(edp_platform.getCustomCode());
		// 订单总价,这里要对运单号进行判断，如果一个运单号对应多个商品，需要对总价进行计算
		order_head.setOrdersum(GetTotalPriceByExpressNumber(order));
		// 订单实际销售价格
		order_head.setGoodsvalue(order_head.getOrdersum());
		// 收件人名称
		order_head.setCollectionusername(order.getReceiverName());
		// 收件人地址
		order_head.setCollectionuseraddress(order.getReceiverAddress());
		// 订单编号,同运单号
		order_head.setOrderid(order.getExpressNumber().replaceFirst("LVS", ""));
		// 发货人所在国（海关代码）
		order_head.setSendusercountry("142");
		// 发货人的名称
		order_head.setSendusername(order.getShipper());
		// 进出口标示
		order_head.setIetype(waybill.getIdType());
		// 操作类型
		order_head.setModifymark(waybill.getModifyMask());
		// 电商检验检疫CIQ备案编号
		order_head.setCbecodeinsp(waybill.getCbeCodeInsp());
		// 订单提交时间
		Calendar calendar = Calendar.getInstance();
		Random rdm = new Random();
		calendar.add(Calendar.DAY_OF_YEAR, -1);
		calendar.add(Calendar.MINUTE, rdm.nextInt(100));
		order_head.setSubmittime(calendar.getTime());
		calendar.add(Calendar.MINUTE, 50);
		order_head.setAddtime(calendar.getTime());
		// 根据国家简称，获取收货人和发货人的国家信息
		Tbcuscountry country = DictionaryHelper.GetCountryByAbbre(order.getState());
		// 收货人所在国（检验检疫代码）
		order_head.setSendusercountryinsp(country.getCountrycode());
		// 收货人所在国（海关代码）
		order_head.setCollectionCountryCus(country.getCustomscode());
		// 发货人所在国（检验检疫代码）
		country = DictionaryHelper.GetCountryByAbbre("CN");
		order_head.setCollusercountryinsp(country.getCountrycode());
		// 支付交易号 选填
		// 其他支付金额 选填
		// 其他支付备注 选填-
		// 许可证号 选填 涉证商品必填
		// 报关企业海关备案编码,默认华商
		order_head.setDeclcode(SystemConstants.Declare_Code_Cus);
		// 报关企业名称
		order_head.setDeclname(SystemConstants.Declare_Name);
		// 成交币制（海关代码）
		Tbciqmoney coin = DictionaryHelper.GetCoinByAbbreviation(order.getCurrency());
		order_head.setCoin(coin.getCustomscode());
		order_head.setCoinInsp(coin.getCountrycode());
		// 征退类型 1、不征不退2、出口退税,默认1
		Tbdictionary dictionary = DictionaryHelper.GetDefaultValue(DictionaryType.ChargingType);
		order_head.setChargetype(dictionary.getDictionariecode());
		// EXTENDFIELD3
		// EXTENDFIELD4
		// EXTENDFIELD5
		order_head.setSendstatus("send");
		order_head.setBatchnumber(order.getSerialNumber());
		/// 国检总局报关企业备案号
		order_head.setInspdeclarecode(SystemConstants.Declare_Code_InSp);

		/// 国检总局物流企业备案号
		order_head.setWlqycodeinsp(logistic.getCiqCode());
		/// 物流企业名称（国检）
		order_head.setDeliverenterprisename(logistic.getLogisticName());
		/// 优惠减免金额(国检) 有值就填，无值默认0
		order_head.setDiscount(new BigDecimal(0));
		/// 订单商品运费（国检）有值就填，无值默认0
		order_head.setFreight(new BigDecimal(0));
		/// 进出口标志（国检）
		order_head.setIeflag("O");
		/// 电商平台名称
		order_head.setEcpname(edp_company.getName());
		order_head.setEcpcodeinsp(edp_company.getCiqCode());
		return order_head;
	}

	public Tbpayinfo GeneratePayInfo(Tbuploaddetail order, Tbedpinfo edp_company, Tbedpinfo edp_platform,
			Tblogisticinfo logistic, Tborderhead order_head) {
		Tbpayinfo pay_info = new Tbpayinfo();
		pay_info.setUploadid(order.getUploadId());
		pay_info.setExpressnumber(order.getExpressNumber());
		// 付款请求序列号
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
		String guid = "PAY" + df.format(new Date());
		pay_info.setGuid(guid);
		pay_info.setPaynumber(guid);
		// 模式代码
		pay_info.setBillmode(DictionaryHelper.GetDefaultValue(DictionaryType.BillMode).getDictionariecode());
		// 收款时间
		Calendar calendar = Calendar.getInstance();
		Random rand = new Random();
		calendar.add(Calendar.MINUTE, rand.nextInt(100));
		pay_info.setPaytime(calendar.getTime());
		pay_info.setOrderid(order.getExpressNumber());
		// 收款类型
		pay_info.setPaymenttype(DictionaryHelper.GetDefaultValue(DictionaryType.PaymentType).getDictionariecode());
		// 币制，同客户币制
		Tbciqmoney coin = DictionaryHelper.GetCoinByAbbreviation(order.getCurrency());
		pay_info.setMonetarytype(coin.getCustomscode());
		// 收款费用，同成交总价
		pay_info.setFee(order_head.getOrdersum());
		// 进出口标志，默认E
		pay_info.setIetype(DictionaryHelper.GetDefaultValue(DictionaryType.IeType).getDictionariecode());
		// 电商企业海关代码
		// 操作类型，默认1，MODIFYMARK
		pay_info.setModifymark(DictionaryHelper.GetDefaultValue(DictionaryType.ModifyMask).getDictionariecode());
		pay_info.setRemark("");
		// 电商企业海关代码
		pay_info.setCbecode(edp_company.getCustomCode());
		// 国检总局电商备案号
		pay_info.setInspCbeCode(edp_company.getCiqCode());
		pay_info.setSendstatus("send");
		return pay_info;
	}

	public Tborderlist GenerateSingleOrderList(Tbuploaddetail _detail, Tbwaybill waybill, int seq_no,
			Tbcuscountry country) {
		Tborderlist order_body = new Tborderlist();
		order_body.setExpressnumber(_detail.getExpressNumber());
		// 商品上架品名
		order_body.setShelfgoodsname(_detail.getProductName());
		// 商品货号,随机生成
		String guid = UUID.randomUUID().toString().substring(0, 5);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
		String random = df.format(new Date()) + guid;
		order_body.setGoodid(random);
		// 申报品名
		order_body.setGoodname(_detail.getProductName());
		// 规格型号，可以同品名，可以写“无”
		order_body.setSpecifications("无");
		// HS编码,取前四位，
		Tbgoodsinfo goods = GoodsHelper.GetGoodsInfo(_detail.getProductName());
		if (goods != null) {
			String hscode = goods.getHscode();
			order_body.setBarcode(hscode.length() > 4 ? hscode.substring(0, 4) : hscode);
			// 计量单位（海关代码）
			order_body.setUnit(goods.getUnit());
			// 法定第一计量单位（海关代码）
			order_body.setUnit1(goods.getUnit1());
		}
		order_body.setSeqno(seq_no);
		order_body.setHscode(order_body.getBarcode());
		// 根据国家
		order_body.setCountryofdestination(country.getCustomscode());
		// 币制（海关代码）
		Tbciqmoney coin = DictionaryHelper.GetCoinByAbbreviation(_detail.getCurrency());
		order_body.setCoin(coin.getCustomscode());
		order_body.setCoininsp(coin.getCountrycode());
		// 净重,单位千克
		order_body.setNetweight(new BigDecimal(_detail.getNetWeight()));
		// 申报数量
		order_body.setAmount((int) Double.parseDouble(_detail.getCount()));
		String unit = goods.getUnit();
		String unit1 = goods.getUnit1();
		// 法定第一数量,要根据法定第一单位进行换算
		if (unit.equals("7")) {
			goods.setUnit("007");
		}
		Tbbcusunit cus_unit = DictionaryHelper.GetCusUnitByCode(goods.getUnit1());
		BigDecimal factor = unit.equals(unit1) ? new BigDecimal(1) : cus_unit.getFactor();
		switch (UnitCategory.values()[cus_unit.getCategory()]) {
		case Weight:
			order_body.setAmount1(factor.multiply(order_body.getNetweight()));
			break;
		case Count:
			order_body.setAmount1(factor.multiply(new BigDecimal(order_body.getAmount())));
			break;
		case Area:
			order_body.setAmount1(factor.multiply(new BigDecimal(order_body.getAmount())));
			break;
		case Volume:
			order_body.setAmount1(factor.multiply(new BigDecimal(order_body.getAmount())));
			break;
		case Length:
			order_body.setAmount1(factor.multiply(new BigDecimal(order_body.getAmount())));
			break;
		default:
			order_body.setAmount1(factor.multiply(new BigDecimal(order_body.getAmount())));
			break;
		}

		// 成交单价
		BigDecimal total_price = new BigDecimal(_detail.getTotalPrice());
		BigDecimal price = total_price.divide(new BigDecimal(order_body.getAmount()), 4, RoundingMode.HALF_UP);
		order_body.setGoodprice(price);
		// 交易价格 ,即交易总价
		order_body.setOrdersum(total_price);
		// 是否赠品 N:不是 Y:是
		order_body.setFlag("N");
		// 币制（检验检疫代码）,国检的代码跟海关的代码不一致，请注意
		order_body.setCoininsp(coin.getCountrycode());
		// 计量单位（检验检疫代码）
		order_body.setUnitinsp(order_body.getUnit());
		// -原产国（检验检疫代码）,默认156
		order_body.setSrccountryinsp("156");
		order_body.setCommbarcode("无");
		// order_body.setseq
		// GetTotalNetWeightOfOrder(_detail);
		return order_body;
	}

	public TbInventoryBody GenerateSingleInventoryBody(Tbuploaddetail _detail, Tbwaybill waybill, int seq_no,
			Tbcuscountry country) {
		TbInventoryBody order_body = new TbInventoryBody();
		// 收款单号
		// order_body.set
		// 申报数量
		order_body.setAmount(new BigDecimal(_detail.getCount()));
		// 规格型号
		order_body.setGoodsModel("无");
		// 商品货号,随机生成
		String guid = UUID.randomUUID().toString().substring(0, 5);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
		String random = df.format(new Date()) + guid;
		order_body.setGoodsNo(random);
		// 商品名称（规范申报品名）
		order_body.setGoodsName(_detail.getDeclareName());
		// HS编码,取前四位，
		Tbgoodsinfo goods = GoodsHelper.GetGoodsInfo(_detail.getProductName());
		if (goods != null) {
			String hscode = goods.getHscode();
			order_body.setHsCode(hscode.length() > 4 ? hscode.substring(0, 4) : hscode);
			// 计量单位（海关代码）
			order_body.setUnit(goods.getUnit());
			// 法定第一计量单位（海关代码）
			order_body.setUnit1(goods.getUnit1());
		}
		// 净重
		order_body.setNetWeight(waybill.getNetWeight());
		// 商品上架品名
		order_body.setShelfGoodsName(_detail.getProductName());
		// 商品总价
		order_body.setOrderSum(new BigDecimal(_detail.getTotalPrice()));
		// 原产国（国检）
		order_body.setSrcCountryInsp(country.getCountrycode());
		// 原产国名称（国检）
		order_body.setSrcCountryNameInsp(country.getCountryname());
		// 品牌（国检）
		order_body.setBrand("无");
		// 计量单位名称（国检）
		// order_body.setUnitName();
		// 入区清单编号（国检）
		order_body.setEntryListNumber("");
		// 提运单号（国检）同主单号
		order_body.setDeliveryNumber(waybill.getBillNo());
		// 原产国（海关）
		order_body.setSrcCountry("142");
		// 商品条码（海关）
		order_body.setCommBarCode("无");
		// 最终目的国代码（海关）
		order_body.setCountryOfDestination(country.getCustomscode());
		// 毛重，国检
		order_body.setWeight(waybill.getWeight());
		order_body.setSeqNo(seq_no);
		// 单价(外币)
		order_body.setPrice(new BigDecimal(_detail.getTotalPrice()));
		Tbciqmoney coin = DictionaryHelper.GetCoinByAbbreviation(_detail.getCurrency());
		order_body.setCurrency(coin.getCustomscode());
		String unit = goods.getUnit();
		String unit1 = goods.getUnit1();
		// 法定第一数量,要根据法定第一单位进行换算
		if (unit.equals("7")) {
			goods.setUnit("007");
		}
		Tbbcusunit cus_unit = DictionaryHelper.GetCusUnitByCode(goods.getUnit1());
		BigDecimal factor = unit.equals(unit1) ? new BigDecimal(1) : cus_unit.getFactor();
		switch (UnitCategory.values()[cus_unit.getCategory()]) {
		case Weight:
			order_body.setAmount1(factor.multiply(order_body.getNetWeight()));
			break;
		case Count:
			order_body.setAmount1(factor.multiply(order_body.getAmount()));
			break;
		case Area:
			order_body.setAmount1(factor.multiply(order_body.getAmount()));
			break;
		case Volume:
			order_body.setAmount1(factor.multiply(order_body.getAmount()));
			break;
		case Length:
			order_body.setAmount1(factor.multiply(order_body.getAmount()));
			break;
		default:
			order_body.setAmount1(factor.multiply(order_body.getAmount()));
			break;
		}
		order_body.setUnit(goods.getUnit());
		// 计量单位名称(国检)
		order_body.setUnitName(goods.getUnit());

		return order_body;
	}

	public List<Tborderlist> GenerateOrderList(Tbuploaddetail _detail, Tbwaybill waybill) {
		List<Tborderlist> order_list = new ArrayList<Tborderlist>();
		int seq_no = 1;

		Tbcuscountry country = DictionaryHelper.GetCountryByAbbre(_detail.getState());
		if (detail_table.containsKey(_detail.getExpressNumber())) {
			List<Tbuploaddetail> orders = tbuploadDetailDao.findOrderByExpressNumber(_detail.getExpressNumber(),
					_detail.getUploadId());
			for (Tbuploaddetail tbuploaddetail : orders) {
				order_list.add(GenerateSingleOrderList(tbuploaddetail, waybill, seq_no, country));
				seq_no++;
			}
		} else {
			order_list.add(GenerateSingleOrderList(_detail, waybill, seq_no, country));
		}

		return order_list;
	}

	public TbInventoryHead GenerateInventoryHead(Tborderhead order_head, Tbwaybill waybill, Tbpayinfo pay,
			Tbuploaddetail detail, Tbedpinfo edp_company, Tbedpinfo edp_platform, Tblogisticinfo logistic,
			String weight_unit, int jcbPort, int applyPort, String transferRegionInSp) {
		TbInventoryHead head = new TbInventoryHead();
		head.setAddTime(new Date());
		// 抵运港（国检）
		head.setArrivedPort(waybill.getTransferRegionInsp());
		Tbcuscountry country = DictionaryHelper.GetCountryByCiqCode(waybill.getTransferRegionInsp());
		head.setArrivedPortName(country.getCountryname());
		head.setBatchNumber(order_head.getBatchnumber());
		head.setBillMode(order_head.getBillmode());
		// 海关清单号
		head.setCbeCbillNo("");
		// 入区清单编号（国检） ENTRY_LIST_NUMBER
		String guid = UUID.randomUUID().toString().substring(0, 5);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
		String random = df.format(new Date()) + guid;
		head.setEntryListNumber(random);
		// 电商企业海关编码
		head.setCbeCode(order_head.getCbecode());
		head.setCbeName(order_head.getCbename());
		// 是否退税：1、不征不退2、出口退税
		head.setChargingType(order_head.getChargetype());
		// 收货人国家，国检代码
		head.setCollectionUserCountryInsp(waybill.getCollectionUserCountryInsp());
		head.setCollectionUserTel(waybill.getCollectionUserTelephone());
		head.setConsignee(waybill.getCollectionUserName());
		head.setConsigneeAddress(waybill.getCollectionUserAddress());
		// 收货人国家海关编码
		head.setConsigneeCountry(waybill.getCollectionUserCountry());
		// 发货人地址
		head.setConsignorAddr(waybill.getSenderAddress());
		// 发货人电话
		head.setConsignorTel(waybill.getSenderTelephone());
		// 发货人姓名
		head.setShipper(waybill.getSenderName());
		// 申报人姓名
		head.setContact(SystemConstants.Declare_Name);
		// 申报人电话
		head.setDeclTel(SystemConstants.Declare_User_Tel);
		// 起运国/运抵国（海关）
		head.setCountryCode(country.getCustomscode());
		head.setCurrency(order_head.getCoin());
		Tbciqmoney money = DictionaryHelper.GetCoinByCustomCode(order_head.getCoin());
		head.setCurrencyInsp(money.getCountrycode());
		head.setCurrencyName(money.getMoneyname());
		// 申报口岸(海关编码)
		head.setDeclarePort(waybill.getDeclarePort());
		// 申报口岸(国检编码)DECLAREPORTINSP
		head.setDeclarePortInsp(waybill.getJcbOrderOrPortInsp());
		head.setDeclarePortInsp(SystemConstants.Declare_Port_Insp);
		head.setDeclarePortNameInsp(SystemConstants.Declare_Port_Name_Insp);
		// 报关企业海关编码
		head.setDeclCode(order_head.getDeclcode());
		head.setDeclName(order_head.getDeclname());
		// 电商平台海关编码
		head.setEcpCode(edp_platform.getCustomCode());
		head.setEcpName(edp_platform.getName());
		head.setGuid(UUID.randomUUID().toString().replaceAll("-", ""));
		// 进出境口岸(海关)
		Tbdictionary dict_port = DictionaryHelper.GetValueById(jcbPort);
		head.setIePort(dict_port.getDictionariecode());
		head.setiETime(new Date());
		// 进出境口岸（国检）
		String port_name = dict_port.getDictionariename();
		if (port_name.equals("口岸作业区")) {
			head.setIsnpIePort("41018406");
		} else if (port_name.equals("郑州机办")) {
			head.setIsnpIePort("41010003");
		}
		// 进出口模式（国检）0 一般，1-保税
		head.setImportType(0);
		// 进出口标志（国检）
		head.setInOutFlag("O");
		// 国检清单号
		head.setInspBillNo("");
		// 国检总局电商企业编号
		head.setInspCode(edp_company.getCiqCode());
		// 起运国/运抵国（国检）
		head.setInspCountryCode(waybill.getTransferRegionInsp());
		head.setInspCountryName(country.getCountryname());
		// 国检总局报关企业备案号
		head.setInspDeclCode(SystemConstants.Declare_Code_InSp);
		// 国检总局电商平台编码
		head.setInspEcpCode(edp_platform.getCiqCode());
		// 国检总局物流企业编号
		head.setInspLogisticsCode(logistic.getCiqCode());
		// 收款企业海关编码,非必填
		head.setInspPayCode("");
		// 运输方式（国检）
		Tbdictionary dict_transfertype = DictionaryHelper.GetDefaultValue(DictionaryType.TransportModeCIQ);
		head.setInspTrafWay(dict_transfertype.getDictionariecode());
		// 清单类型(国检)1 进仓(保税备货入区) 2 出仓(保税备货出区) 3 B2C进境(直购)
		head.setListType("2");
		// 物流企业海关编码
		head.setLogisticsCode(logistic.getLogisticCode());
		// 物流企业名称
		head.setLogisticsName(logistic.getLogisticName());
		// 收款单号
		head.setPayNumber(pay.getPaynumber());

		// 操作类型（1-新增；2-修改；3-删除）
		head.setModifymark("1");
		head.setNetWeight(waybill.getNetWeight());
		head.setOrderNo(order_head.getExpressnumber());
		// 包装种类代码(海关)
		head.setPackCategory(waybill.getPackageCategory());
		head.setPackNumber(1);
		// 收款企业海关编码
		head.setPayCode("");
		// 监管机构代码（国检）,同进出境口岸
		head.setRegulatorCode(dict_port.getDictionariecode());
		// 监管机构名称（国检）
		head.setRegulatorName(dict_port.getDictionariename());

		// head.setRemark("");
		// 运输工具代码(海关)
		Tbdictionary dict_ship = DictionaryHelper.GetDefaultValue(DictionaryType.ShipName);
		head.setShipCode(dict_ship.getDictionariecode());
		Tbdictionary dict_ciq_transfertype = DictionaryHelper.GetDefaultValue(DictionaryType.CIQShipName);
		// 运输工具编码（国检）
		head.setShipCodeInsp(dict_ciq_transfertype.getDictionariecode());
		// 运输工具名称
		head.setShipName(dict_ship.getDictionariename());
		head.setShipper(waybill.getSenderName());
		// 发货人城市，非必填
		head.setShipperCity("410100");
		head.setStatus("send");
		head.setSubmitTime(new Date());
		// 总单号
		head.setTotalNumber(waybill.getBillNo());
		// 总货值(外币),暂时不填
		head.setTotalValue(order_head.getOrdersum());
		// 总货值(人民币)
		head.setTotalValueRmb(order_head.getOrdersum());
		// 运输方式（海关）
		dict_transfertype = DictionaryHelper.GetDefaultValue(DictionaryType.TransportMode);
		head.setTrafWay(dict_transfertype.getDictionariecode());
		// 运单编号
		head.setTransferNumber(waybill.getExpressNumber());
		head.setUploadId(waybill.getUploadId());
		// 国检部分
		// 发货人电话
		head.setConsignorTel(waybill.getSenderTelephone());
		// 发货人地址
		head.setConsignorAddr(waybill.getSenderAddress());
		// 销售方式（国检）
		head.setTradeMode("2");
		// 进出口模式
		head.setImportType(0);
		// 进出口类型（海关）I 进口；E 出口
		head.setIeType("E");
		// 发货人国家海关代码
		head.setShipperCountry("142");
		// 外币币制
		Tbciqmoney coin = DictionaryHelper.GetCoinByAbbreviation(detail.getCurrency());
		head.setCurrencyInsp(coin.getCountrycode());
		// 起运国/抵运国（国检）
		head.setInspCountryCode(waybill.getTransferRegionInsp());
		// 装运港/指运港（海关）
		head.setDestinationPort(waybill.getDestinationPort());
		// 装运港/指运港（国检）
		head.setDestinationPortInsp(waybill.getIsnpDestinationPort());
		// 起运国/运抵国（海关）
		head.setCountryCode(waybill.getDestinationCountryCus());

		head.setShipper("河南龙库供应链管理有限公司");
		head.setArrivedPort("554003");
		return head;
	}

	public List<TbInventoryBody> GenerateInventoryBody(Tborderhead order_head, Tbwaybill waybill, Tbpayinfo pay,
			Tbuploaddetail _detail, Tbedpinfo edp_company, Tbedpinfo edp_platform, Tblogisticinfo logistic,
			String weight_unit, int jcbPort, int applyPort, String transferRegionInSp) {
		List<TbInventoryBody> inventory_list = new ArrayList<TbInventoryBody>();
		int seq_no = 1;
		Tbcuscountry country = DictionaryHelper.GetCountryByAbbre(_detail.getState());

		if (detail_table.containsKey(_detail.getExpressNumber())) {
			List<Tbuploaddetail> orders = tbuploadDetailDao.findOrderByExpressNumber(_detail.getExpressNumber(),
					_detail.getUploadId());
			for (Tbuploaddetail tbuploaddetail : orders) {
				inventory_list.add(GenerateSingleInventoryBody(tbuploaddetail, waybill, seq_no, country));
				seq_no++;
			}
		} else {
			inventory_list.add(GenerateSingleInventoryBody(_detail, waybill, seq_no, country));
		}

		return inventory_list;
	}

	public BigDecimal GetTotalPriceByExpressNumber(Tbuploaddetail _detail) {
		BigDecimal result = new BigDecimal(0);
		// 通过判断该运单号是否对应多个商品，减少数据库读取次数
		if (detail_table.containsKey(_detail.getExpressNumber())) {
			List<Tbuploaddetail> orders = tbuploadDetailDao.findOrderByExpressNumber(_detail.getExpressNumber(),
					_detail.getUploadId());
			if (orders != null) {
				for (Tbuploaddetail order : orders) {
					result.add(new BigDecimal(order.getTotalPrice()));
				}
			}

		} else {
			result = new BigDecimal(_detail.getTotalPrice());
		}
		return result;
	}

	public BigDecimal GetStandardWeight(String str_weight, String unit) {
		BigDecimal weight = new BigDecimal(str_weight);
		switch (unit) {
		case "克":
			weight = weight.divide(new BigDecimal(1000), 4, RoundingMode.HALF_UP);
			break;
		case "千克":
			break;
		default:
			break;
		}
		return weight;
	}

	public int GetTotalAmountOfOrder(Tbuploaddetail _detail) {
		int amount = 0;
		if (detail_table.containsKey(_detail.getExpressNumber())) {
			List<Tbuploaddetail> orders = new ArrayList<Tbuploaddetail>();
			if (orders != null) {
				for (Tbuploaddetail order : orders) {
					amount += Integer.parseInt(order.getCount());
				}

			}

		} else {
			amount = (int) Double.parseDouble(_detail.getCount());
		}
		return amount;
	}

	public BigDecimal GetTotalNetWeightOfOrder(Tbuploaddetail upload) {
		BigDecimal net_weight = new BigDecimal(0);
		if (detail_table.containsKey(upload.getExpressNumber())) {
			List<Tbuploaddetail> orders = new ArrayList<Tbuploaddetail>();
			if (orders != null) {
				for (Tbuploaddetail order : orders) {
					net_weight = net_weight.add(new BigDecimal(order.getNetWeight()));
				}
			}
		} else {
			if (upload.getNetWeight() != null && !upload.getNetWeight().isEmpty()) {
				net_weight = new BigDecimal(upload.getNetWeight());
			} else {
				net_weight = new BigDecimal(upload.getRoughWeight()).subtract(new BigDecimal(0.02));
			}
		}
		return net_weight.compareTo(new BigDecimal(0)) < 1 ? new BigDecimal(0.01) : net_weight;
	}

	public List<Tbuploaddetail> GetDuplicateOrder(int upload_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("upload_id", upload_id);
		return tbuploadDetailDao.findDuplicateOrder(map);
	}

	public List<Tbuploaddetail> GetDistinctOrder(int upload_id) {
		return tbuploadDetailDao.findDistinctOrder(upload_id);
	}
}